package br.com.pokertime;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import br.com.pokertime.modelo.Blind;
import br.com.pokertime.modelo.BlindDAO;

/**
 * 
 * @author felipe
 * @since 25/08/2011
 *
 */
public class TelaInicial extends Activity {

	private static final int MENU_BLINDS = 1;
	private TextView textTime;
	private RefreshHandler mRedrawHandler = new RefreshHandler();
	private int minutos;
	private int segundos;
	private boolean pause = true;
	private boolean tempoEsgotado = false;

	class RefreshHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			TelaInicial.this.updateUI();
		}

		public void sleep(long delayMillis) {
			this.removeMessages(0);
			sendMessageDelayed(obtainMessage(0), delayMillis);
		}
		
		public void start(){
			this.handleMessage(obtainMessage(0));
		}
	};

	private void updateUI() {
		if(this.pause == false && this.tempoEsgotado == false){	
			mRedrawHandler.sleep(1000);
			segundos--;
			if(segundos == -1){
				segundos = 59;
				minutos--;			
			}
			validaTempoEsgotado(minutos, segundos);
			exibeTime(minutos, segundos);
		}else{
			mRedrawHandler.sleep(1000);
		}
	}
	
	private void validaTempoEsgotado(int minutos, int segundos){
		if(minutos == 0 && segundos == 0){
			this.tempoEsgotado = true;
		}
	}
	
	private void exibeTime(int minutos, int segundos){
		String textoExibido;
		if(segundos < 10){
			textoExibido = String.valueOf(minutos + ":0" + segundos);
		}else{
			textoExibido = String.valueOf(minutos + ":" + segundos);
		}
		textTime.setText(textoExibido);
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		textTime = (TextView) findViewById(R.id.textTime);
		setTempoPadrao();
		//updateUI();
		test();
	}
	
	public void botaoPauseAction(View view){
		this.pause = true;
	}
	
	public void botaoStartAction(View view){
		if(this.tempoEsgotado == true){
			this.tempoEsgotado = false;
			setTempoPadrao();
			
		}
		this.pause = false;
	}
	
	private void setTempoPadrao(){
		this.minutos = 0;
		this.segundos = 10;
		exibeTime(minutos, segundos);
	}
	
	@Override
	public boolean onCreateOptionsMenu(android.view.Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_BLINDS, 0, "Blinds");
		return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {

		switch (item.getItemId()) {
		case MENU_BLINDS:
			return true;
		}
		return false;
	}
	
	public void test(){
		Blind blind = new Blind();
		blind.setBigBlind(10);
		blind.setNivel(1);
		blind.setSmallBlind(4);
		BlindDAO blindDAO = new BlindDAO(getApplicationContext());
		blindDAO.insert(blind);
		
		List lista = blindDAO.getAllBlinds();
		lista.get(0);
		
	}
}